# Tool to replace anim.dat file in every .tar.gz in the res directory
# This is needed during update the animation files to the new version of the animation library
# and probably needed in the future.


import os, sys, shutil
import tarfile

__AUTHOR__ = "cookie"
__VERSION__ = "1.0"

#start_folder = os.path.join ("Users"..", "res")        # start-folder for the search
start_folder = "/Users/michael/Desktop/res"
file_pattern = "tar.gz"                          # Find all files
old_animdat  = "anim.dat"
new_animdat  = "anim3.dat" 

def delete_tmp_folder ():
    for l in os.listdir("tmp"):
        os.unlink (os.path.join ("tmp",l))
    os.rmdir("tmp")
    os.unlink("tmp")

def create_tmp_folder ():
    try:
        delete_tmp_folder()
    except:
        pass
    os.mkdir("tmp")
    
def replace_animdat (curdir, filename):

    create_tmp_folder()
    
    # extract tar in tmp
    try:
        os.mkdir("tmp")
    except:
        pass
    tar = tarfile.open (os.path.join (curdir,filename),"r")
    tar.extractall ("tmp")
    tar.close()
    
    # create new animdat
    o = open (os.path.join ("tmp", old_animdat))
    n = open (os.path.join ("tmp", new_animdat), "w")
    
    n.write ("Set_Parameter (True, True, (255,0,255), 1.0)\n")
    c=0
    for line in o:
        l = line.split (";")
        if len(l) > 1:
            s = "Frame (" + str(c) + ", '"+ str(l[1]) + "', 0)\n"
        if len(l) > 2 and l[2] == "1":
            s = s + "Hotspot (" +l[3] +"," + l[4]+ ")\n"
        n.write (s)
        c+=1
        
    o.close()
    n.close()

    # create new archive
    os.chdir("tmp")
    tar2 = tarfile.open (filename, "w:gz")
    tar2.add (".")
    tar2.close()    
    os.chdir("..")

    # overwrite old file
    os.unlink (os.path.join (curdir,filename))
    shutil.move(os.path.join("tmp", filename), os.path.join (curdir, filename))
    return
 
# Change to start path
os.chdir (start_folder) 
 
result_list = []
# recurse all folders
for res in os.walk ("."):
    curdir, dirs, files = res
    # see if we have found files matching the pattern or continue
    r = [i for i in files if i.endswith (file_pattern)]
    if r == []:
        continue
    result_list.append ((curdir, r))

print result_list

for i in result_list:
    curdir, files = i
    for j in files:
        print curdir, j
        replace_animdat (curdir, j)

# clean up
try:
    delete_tmp_folder()
except:
    pass